package com.cmccgz.udacs_landlord_webapp.main.accreditmanager;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.cmccgz.baselibrary.utils.RegularUtil;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.ApiService;
import com.cmccgz.udacs_landlord_webapp.base.GlobalContext;
import com.cmccgz.udacs_landlord_webapp.bean.IdBean;
import com.cmccgz.udacs_landlord_webapp.bean.ResultBean;
import com.cmccgz.udacs_landlord_webapp.data.IdScanDataRepository;
import com.cmccgz.udacs_landlord_webapp.data.IdScanDataSource;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import rx.Subscriber;

/**
 * 开卡授权Presenter
 */
public class AddPersonPresenter implements AddPersonContract.Presenter {
    private Timer timer;
    private int waitTime = 60;
    private boolean isWaiting=false;

    private AddPersonContract.View contentView;
    private String[] nations ;

    private IdScanDataRepository idScanDataRepository;
    private Map<String, String> map;

    public AddPersonPresenter(@NonNull AddPersonContract.View contentView) {
        this.contentView = contentView;
        this.contentView.setPresenter(this);
        initNations();
    }

    @Override
    public void start() {

    }

    @Override
    public void selectNation() {
        initNations();
        contentView.showAllNation(nations);
    }

    private void initNations() {
        if (nations==null) {
            map = new HashMap<>();
            map.put("汉族","01");
            map.put("蒙古族","02");
            map.put("回族","03");
            map.put("藏族","04");
            map.put("维吾尔族","05");
            map.put("苗族","06");
            map.put("彝族","07");
            map.put("壮族","08");
            map.put("布依族","09");
            map.put("朝鲜族","10");
            map.put("满族","11");
            map.put("侗族","12");
            map.put("瑶族","13");
            map.put("白族","14");
            map.put("土家族","15");
            map.put("哈尼族","16");
            map.put("哈萨克族","17");
            map.put("傣族","18");
            map.put("黎族","19");
            map.put("傈僳族","20");
            map.put("佤族","21");
            map.put("畲族","22");
            map.put("高山族","23");
            map.put("拉祜族","24");
            map.put("水族","25");
            map.put("东乡族","26");
            map.put("纳西族","27");
            map.put("景颇族","28");
            map.put("柯尔克孜族","29");
            map.put("土族","30");
            map.put("达斡尔族","31");
            map.put("仫佬族","32");
            map.put("羌族","33");
            map.put("布朗族","34");
            map.put("撒拉族","35");
            map.put("毛南族","36");
            map.put("仡佬族","37");
            map.put("锡伯族","38");
            map.put("阿昌族","39");
            map.put("普米族","40");
            map.put("塔吉克族","41");
            map.put("怒族","42");
            map.put("乌孜别克族","43");
            map.put("俄罗斯族","44");
            map.put("鄂温克族","45");
            map.put("德昂族","46");
            map.put("保安族","47");
            map.put("裕固族","48");
            map.put("京族","49");
            map.put("塔塔尔族","50");
            map.put("独龙族","51");
            map.put("鄂伦春族","52");
            map.put("赫哲族","53");
            map.put("门巴族","54");
            map.put("珞巴族","55");
            map.put("基诺族","56");
            map.put("穿青人","59");
            map.put("亻革家人","60");
            map.put("外国血统","98");
            map.put("其它","99");
            ArrayList<String> nationsList = new ArrayList<>(map.keySet());
            Collections.sort(nationsList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    try {
                        String num1 = map.get(o1);
                        String num2 = map.get(o2);
                        return Integer.parseInt(num1)-Integer.parseInt(num2);
                    } catch (NumberFormatException e) {
                        return 0;
                    }
                }
            });
            nations = nationsList.toArray(new String[nationsList.size()]);
        }
    }

    @Override
    public void confirmPersonInfo(String mobile,String houseId, String usermobile, String name, String sex, String idCard, String nation,String address, String birth, String houseNo, String verify) {
        if (TextUtils.isEmpty(mobile)) {
            //TODO
            return;
        }
        Logger.d(usermobile);
        if (TextUtils.isEmpty(usermobile)) {
            contentView.showEmptyMobile();
            return;
        }

        if (!RegularUtil.isMobileNumber(usermobile)) {
            contentView.showInvalidMobile();
            return;
        }

        if (TextUtils.isEmpty(name)) {
            contentView.showEmptyName();
            return;
        }
        if (name.length() < 2 || name.length() > 30) {
            contentView.showInvalidName();
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            contentView.showEmptyIdCard();
            return;
        }
        if (!RegularUtil.isIDCardNumber(idCard)) {
            contentView.showInvalidIdNumber();
            return;
        }
        String nationNum = getNationNum(nation);
        if (TextUtils.isEmpty(nationNum)) {
            contentView.showEmptyNation();
            return;
        }
        if (TextUtils.isEmpty(birth)) {
            contentView.showEmptyBirthDate();
            return;
        }
        if(TextUtils.isEmpty(houseNo)){
            contentView.showEmptyHouseNo();
            return;
        }
        if(TextUtils.isEmpty(verify)){
            contentView.showEmptyVerify();
            return;
        }
        contentView.showLoadingDialog();
        ApiService.addRenter(mobile,houseId,usermobile,name,sex,idCard,nationNum,address,birth,houseNo,verify).subscribe(new Subscriber<ResultBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                contentView.compeleError("新增人员失败，请稍后再试！");
            }

            @Override
            public void onNext(ResultBean resultBean) {
                if ("0".equals(resultBean.rsmsg.rscode)) {
                    contentView.compeleSuccess();
                }else{
                    contentView.compeleError(resultBean.rsmsg.rsdesc);
                }
            }
        });
    }
    private String getNationNum(String nation){
        if (StringUtils.isEmpty(nation)||map==null) {
            return null;
        }
        return !StringUtils.isEmpty(map.get(nation))?map.get(nation):!StringUtils.isEmpty(map.get(nation+"族"))?map.get(nation+"族"):null;
    }
    @Override
    public void scanId(String imgUrl) {
        if (idScanDataRepository==null) {
            idScanDataRepository = new IdScanDataRepository();
        }
        idScanDataRepository.scanId(imgUrl, new IdScanDataSource.IdScanLisenter() {
            @Override
            public void scanIdSuccess(IdBean idBean) {
                contentView.scanIdSuccess(idBean);
            }

            @Override
            public void scanIdError(String msg) {
                contentView.scanIdError(msg);
            }
        });
    }

    @Override
    public void getCode(String mobile, Handler handler) {
        Context context = GlobalContext.getInstance();
        if (!RegularUtil.isMobileNumber(mobile)) {
            contentView.getCodeError(context.getString(R.string.tips_phone_error));
            return;
        }

        startWaiting(handler);

        //getcode
        ApiService.getSms(mobile,"2").subscribe(new Subscriber<ResultBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                stopWaiting();
                contentView.getCodeError("获取验证码失败！");
            }

            @Override
            public void onNext(ResultBean resultBean) {
                if ("0".equals(resultBean.rsmsg.rscode)) {
                    contentView.getCodeSuccess();
                }else{
                    stopWaiting();
                    contentView.getCodeError(resultBean.rsmsg.rsdesc);
                }
            }
        });
    }
    public void startWaiting(final Handler handler) {
        if (timer != null) {
            timer.cancel();
        }
        waitTime = 60;
        contentView.waitCode(waitTime );
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                waitTime--;
                if (handler != null) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.e("INX", "waitTime: isWaiting="+isWaiting+",waitTime="+waitTime );

                            if (!isWaiting) {
                                return;
                            }
                            contentView.waitCode(waitTime );
                        }
                    });
                }
                if (waitTime <= 0) {
                    timer.cancel();
                }
            }
        }, 1000, 1000);
        isWaiting=true;
    }

    public void stopWaiting() {
        if (timer!=null) {
            timer.cancel();
        }
        timer=null;
        contentView.resetCode();
        isWaiting=false;
    }
}
